<?php
include_once("../configure/admin.config.inc.php");	//--> admin global var
include_once("db.inc.php");							//--> db global var
include_once("Smarty.class.php");					//--> out template
include_once("Operation.php");						//--> Operation
include_once("Product.php");						//--> Product
include_once("CSVFileParser.php");					//--> CSVFileParser
include_once("Files.php");							//--> Files
include_once("UploadFiles.php");					//--> UploadFiles
include_once("Files.php");							//--> Files
require_once("controlHeader.php");					//--> system control header

$objOperate = new Operation($objSession->getLanguage());	//--> Operation
$oProduct 	= new Product(DB_TAG_PUBLIC, $uid);				//--> Product
$oFiles 	= new Files();									//--> CSVFileParser
$oCSVParser = new CSVFileParser();							//--> CSVFileParser

$objUploadFiles	= new UploadFiles(DB_TAG_PUBLIC, $uid);	//--> UploadFiles
$objFiles		= new Files(DB_TAG_PUBLIC, $uid);		//--> Files

$arrCheckResult 	= array();

$arrAllRelatedNew	= array();
$arrRelatedPNamePID		= array();

$error_message 		= '';
$batchFile			= '';
$checkOK			= 'yes';

$arrOperate = $objOperate->arrGetFromGroupIDAndMenuID($gid, $menuid);

$arrProducts 	= array();
$sql		 	= "SELECT name, productID FROM products_description";
$arrAllProducts = $oProduct->getHash(DB_TAG_PUBLIC, $sql);

foreach($arrAllProducts as $key => $value){
	$arrProducts[ strtolower($key)] =$value;
}

if(isset($_POST['Submit'])){
	if(isset($_FILES['batchFile']['name'])){
		$file_name 	= $_FILES['batchFile']['name'];
		$file_tmp  	= $_FILES['batchFile']['tmp_name'];
		
		$batchFile = "../../batchfiles/batchProductFile." . date('Ymdhis') . '.csv';
	
		if(!empty($file_name)){
			if (!copy($file_tmp, $batchFile)) {//-- save file
				$error_message = "upload file failure : $file_name";
			}
		}
	}else if($_POST['Submit'] == "Confirm Submit"){
		$file_tmp  	= $_POST['batchFile'];
		
		$batchFile	= $_POST['batchFile'];
	}
	
	
	if(empty($error_message)){
		$oCSVParser->parser($batchFile);
		
		$arrNameList = $oCSVParser->getNameList();// csv file product name list
		
		$arrRelatedNew	= array();
		
		while(!$oCSVParser->isEnd()){
			$oCSVParser->nextLine();
			
			$colorAttributeID	= 0;
			$manufacturerID		= 0;
			$categoryID 		= 0;
			$totalCount			= 0;
			$taxRateID			= 1;
			$shippingTypeID		= 0;
			
			$arrSizeID		= array();
			$arrVisorID		= array();
			$arrRelatedPID	= array();
			$arrImages		= array();
			
			$name 			= $oCSVParser->getValue('name');
			$URL 			= $oCSVParser->getValue('url');
		 	$description	= $oCSVParser->getValue('description');
			$price			= $oCSVParser->getValue('price');
			$weight			= $oCSVParser->getValue('weight');
			$model			= $oCSVParser->getValue('model');
			$manufacturer	= $oCSVParser->getValue('manufacturer');
			$size			= $oCSVParser->getValue('size');
			$visor			= $oCSVParser->getValue('visor');
			$color			= $oCSVParser->getValue('color');
			$related		= $oCSVParser->getValue('related');
			$UPC			= $oCSVParser->getValue('upc');
			$images			= $oCSVParser->getValue('images');
			$category		= $oCSVParser->getValue('category');
			
			$mainImage		= $oCSVParser->getValue('mainimage');
			$shippingType	= $oCSVParser->getValue('shippingtype');
			
			$arrinfo = array();
			
			if(empty($name)){
				$arrinfo[] = 'Product name <font color="#FF0000"> is required. </font>';
				
				continue;
			}else if(empty($description)){
				$arrinfo[] = 'Product description <font color="#FF0000"> is required. </font>';
			}else if(empty($price)){
				$arrinfo[] = 'Product price <font color="#FF0000"> is required. </font>';
			}else if(empty($color)){
				$arrinfo[] = 'Product color <font color="#FF0000"> is required. </font>';
			}else if(empty($images)){
				$arrinfo[] = 'Product images <font color="#FF0000"> is required. </font>';
			}else {
				
				
			}
			
			// check product existed?
			if(!empty($name)){
				if(array_key_exists(strtolower($name), $arrProducts)){
					$arrinfo[] = "<b>product name existed </b>: <font color='#FF0000'>$name </font> in Site.";
				}
				
				if(array_key_exists($name, $arrNameList)){
					$arrKeys = array_keys($arrNameList, $name);
					if(count($arrKeys) > 1)
						$arrinfo[] = "<b>product name repeat </b>: <font color='#FF0000'>$name </font>";
				}
			}
			
			
			// check manufacturer
			if(!empty($manufacturer)){
				$sql = "SELECT id FROM manufacturers WHERE name = '$manufacturer'";
				
				$manufacturerID = $oProduct->getColumn(DB_TAG_PUBLIC, $sql);
				if(empty($manufacturerID)){
					$arrinfo[] = "<b>not found manufacturer</b>: <font color='#FF0000'>$manufacturer </font>";
				}
			}
			
			// check shippingType
			if(!empty($shippingType)){
				$sql = "SELECT id FROM shipping_type WHERE name = '$shippingType'";
				
				$shippingTypeID = $oProduct->getColumn(DB_TAG_PUBLIC, $sql);
				
				if(empty($shippingTypeID)){
					$arrinfo[] = "<b>not found shipping Type</b>: <font color='#FF0000'>shippingType </font>";
				}
			}
			
			// check category
			if(!empty($category)){
				$sql = "SELECT id FROM info_class WHERE name = '$category'";
				
				$categoryID = $oProduct->getColumn(DB_TAG_PUBLIC, $sql);
				if(empty($categoryID)){
					$arrinfo[] = "<b>not found category</b>: <font color='#FF0000'>$category </font>";
				}
			}
			
			// check color
			if(!empty($color)){
				$sql = "SELECT id FROM attributes WHERE parentID = 33 AND name = '$color'";
				
				$colorAttributeID = $oProduct->getColumn(DB_TAG_PUBLIC, $sql);
				if(empty($colorAttributeID)){
					$arrinfo[] = "<b>not found color</b>: <font color='#FF0000'>$color </font>";
				}
			}
			
			// check size
			if(!empty($size)){
				$arrSize = explode(',', $size);
				
				foreach($arrSize as $sizename){
					$sql = "SELECT id FROM attributes WHERE parentID = 1 AND name = '$sizename'";
					
					$sizeAttributeID = $oProduct->getColumn(DB_TAG_PUBLIC, $sql);
					if(empty($sizeAttributeID)){
						$arrinfo[] = "<b>not found size</b>: <font color='#FF0000'>$sizename. </font>";
					}else{
						$arrSizeID[] = $sizeAttributeID;
					}
				}
			}
			
			// check visor
			if(!empty($visor)){
				$arrVisro = explode(';', $visor);
				
				foreach($arrVisro as $visorname){
					$arrVisorPrice = explode('/', $visorname);
					
					$sql = "SELECT id FROM attributes WHERE parentID = 4 AND name = '" . $arrVisorPrice[0] . "'";
					
					$visorAttributeID = $oProduct->getColumn(DB_TAG_PUBLIC, $sql);
					if(empty($visorAttributeID)){
						$arrinfo[] = "<b>not found visor</b>: <font color='#FF0000'>" . $arrVisorPrice[0] . " </font>";
					}else{
						if(count($arrVisorPrice) > 1){
							if(is_numeric($arrVisorPrice[1]))
								$arrVisorID[$visorAttributeID] = $arrVisorPrice[1] * 100;
							else
								$arrinfo[] = "<b>visor price format error </b>: <font color='#FF0000'>" . $arrVisorPrice[1] . " </font>";
						}else
							$arrVisorID[$visorAttributeID] = 0;
					}
				}
			}
			
			// check images
			if(!empty($images)){
				$arrUploadImages = explode(',', $images);
				
				$imageDIR = "../../batchImages";
				
				$arrFileNameList = $oFiles->listFileName($imageDIR);
				
				foreach($arrUploadImages as $imagename){
					if(!in_array($imagename, $arrFileNameList)){
						$arrinfo[] = "<b>not found image</b> : <font color='#FF0000'>$imagename.</font>";
					}else{
						$md5 = md5(file_get_contents($imageDIR . "/$imagename"));
						
						$imageid = $objUploadFiles->isExisted($arrOperate, UploadFiles::TYPE_IMAGE, $md5);
						if(!empty($imageid) && $_POST['Submit'] != "Confirm Submit"){
							$productIDs = $oProduct->productIDsOfImage($arrOperate, $imageid);
							
							$arrinfo[] = "<b>image existed </b> <font color='#FF0000'>$imagename</font> with product ID list [ $productIDs ]";
						}else{
							$imageinfo = getimagesize($imageDIR . "/$imagename");
							
							$arr_image_extend_name 	= explode('/', $imageinfo['mime']);
							$image_extend_name 		= $arr_image_extend_name[count($arr_image_extend_name) - 1];
							
							$arrImage = array();
							$arrImage['name'] 		= $imagename;
							$arrImage['file_path'] 	= $imageDIR . "/$imagename";
							$arrImage['file_size']	= filesize($imageDIR . "/$imagename");
							
							$arrImage['width']		= $imageinfo[0];
							$arrImage['height']		= $imageinfo[1];
							
							$arrImage['md5']		= $md5;
							$arrImage['extName']	= $image_extend_name;
							
							$arrImages[] 			= $arrImage;
						}
					}
				}
			}
			
			// check related
			if(!empty($related)){
				$arrRelated = explode(',', $related);
				
				foreach($arrRelated as $relatedName){
					if(!array_key_exists(strtolower($relatedName), $arrProducts)){
						if(!in_array($relatedName, $arrNameList)){
							$arrinfo[] = "<b>not found related product</b> : <font color='#FF0000'>$relatedName. </font>";
						}else{
							$arrRelatedNew[] = $relatedName;
						}
					}else{
						$arrKeys = array_keys($arrProducts, strtolower($relatedName));
						
						foreach($arrKeys as $key){
							$arrRelatedPID[] = $arrProducts[$key];
						}
					}
				}
			}
			

			if(count($arrinfo) == 0){
				if($_POST['Submit'] == "Confirm Submit"){
					$strStatus 	= 'normal';
					
					$productID 	= $oProduct->add($arrOperate, $categoryID, $price, $weight, $totalCount, $model, $manufacturerID, $taxRateID, $UPC, $URL, $LANGEUAGE_ID, $name, $description, $strStatus, $shippingTypeID);
					if($productID){
						$oProduct->addAttribute($arrOperate, $productID, $colorAttributeID, 0);
						
						foreach($arrSizeID as $sizeid){
						 	$oProduct->addAttribute($arrOperate, $productID, $sizeid, 0);
						}
						
						foreach($arrVisorID as $visorid => $visorPrice){
						 	$oProduct->addAttribute($arrOperate, $productID, $visorid, $visorPrice);
						}
						
						foreach($arrRelatedPID as $relatedPid){
							if($productID != $relatedPid){
								$sql = "INSERT INTO products_related SET type = 1,  productID = $productID, relatedProdID = $relatedPid ON DUPLICATE KEY UPDATE relatedProdID = VALUES(relatedProdID)";
						 		$oProduct->update(DB_TAG_PUBLIC, $sql);
							}
						}
						
						foreach ($arrImages as $arrImg) {
							$isMain = 'no';
							
							if($arrImg['name'] == $mainImage)
								$isMain = 'yes';
								
							$imageid = $objUploadFiles->add($arrOperate, UploadFiles::TYPE_IMAGE, $arrImg['extName'], $arrImg['md5'], $arrImg['width'], $arrImg['height'], $arrImg['file_size']);
							
							$oProduct->addImage($arrOperate, $productID, $imageid, $colorAttributeID, $isMain);
							
							$imageName = $imageid . '.' . strtolower($arrImg['extName']);
							
							if (!copy($arrImg['file_path'], $objFiles->getFullPathByID(PRODUCT_IMAGE_DIR, $imageid, $imageName))) {//-- save image
								$error_message = "copy image failure.";
							}
						}
						
						if(count($arrRelatedNew) > 0)
							$arrAllRelatedNew[$productID]	= $arrRelatedNew;
						
						$arrRelatedPNamePID[$name]			= $productID;
					}
					
					$arrinfo[] 	= ">>>>><font color='#26B912'> Complete to add new products.</font>";
					
					$checkOK = 'no';
				}else{
					$arrinfo[] 	= ">>>>><font color='#26B912'> not found error, can write to Site.</font>";
				}
			}else
				$checkOK	= 'no';
				
			
			if(array_key_exists($name, $arrCheckResult)){
				$arrCheckResult[$name] = array("<b>product name repeat </b>: <font color='#FF0000'>$name </font>");
			}else{
				$arrCheckResult[$name] = $arrinfo;
			}
			
		}
	}
	
}

foreach ($arrAllRelatedNew as $productID => $arrRelated) {
	foreach ($arrRelated as $relatedpName) {
		$relatedPid = $arrRelatedPNamePID[$relatedpName];
		
		if(empty($relatedPid))
			$error_message .= "related product add error. not found related product ID, product ID $productID";
		else if($productID != $relatedPid){
			$sql = "INSERT INTO products_related SET type = 1,  productID = $productID, relatedProdID = $relatedPid ON DUPLICATE KEY UPDATE relatedProdID = VALUES(relatedProdID)";
	 		$oProduct->update(DB_TAG_PUBLIC, $sql);
		}
	}
}

if(count($arrCheckResult) == 0)
	$checkOK = 'no';
	
/*----- out html -----*/
$smarty = new Smarty();					//----- out template
$smarty->template_dir = TEMPLATE_SYS_DIR;
$smarty->compile_dir  = COMPILE_SYS_DIR;

$smarty->assign('error_message', $error_message);
$smarty->assign('menuGid', $menuGid);
$smarty->assign('menuid', $menuid);

$smarty->assign('checkOK', $checkOK);

$smarty->assign('batchFile', $batchFile);
$smarty->assign('arrCheckResult', $arrCheckResult);

$smarty->display('batchProduct.htm');
?>
